﻿using System;
using System.Linq;
using Dgg.Anug.Cqrs.Core.Domain.Admin.Events;
using Dgg.Anug.Cqrs.Core.Infrastructure.Data;
using Dgg.Anug.Cqrs.Core.Infrastructure.Eventing;
using Raven.Client;

namespace Dgg.Anug.Cqrs.Core.Application.Admin.Services.Handlers
{
	public class SolutionRenamedPersister : IHandler<SolutionRenamed>
	{
		private readonly IEventSession _eventSession;

		public SolutionRenamedPersister(IEventSession eventSession)
		{
			_eventSession = eventSession;
		}

		public bool Handle(SolutionRenamed e)
		{
			_eventSession.Save(e);
			return true;
		}
	}

	public class SolutionRenamedQueryUpdater : IHandler<SolutionRenamed>
	{
		private readonly IDocumentSession _modelSession;

		public SolutionRenamedQueryUpdater(IDocumentSession modelSession)
		{
			_modelSession = modelSession;
		}

		public bool Handle(SolutionRenamed e)
		{
			var model = _modelSession.Single<Presentation.Models.Admin.Solution>(e.ReceiverId);
			model.Name = e.NewName;
			
			return true;
		}
	}

	public class RenameForAssignedVersionQueryUpdater :  IHandler<SolutionRenamed>
	{
		private readonly IDocumentSession _modelSession;

		public RenameForAssignedVersionQueryUpdater(IDocumentSession modelSession)
		{
			_modelSession = modelSession;
		}

		public bool Handle(SolutionRenamed e)
		{
			string indexName = typeof (Queries.VersionsAssignedToSolution).Name;
			Presentation.Models.Admin.AppVersion[] assignedVersions = _modelSession.Query<Presentation.Models.Admin.AppVersion>(indexName)
					.Where(v => v.AssignedTo.Id == e.ReceiverId.ToString())
					.ToArray();

			Array.ForEach(assignedVersions, version => version.AssignedTo.Name = e.NewName);

			return true;
		}
	}

	public class RenameForAssignedBuildsQueryUpdater : IHandler<SolutionRenamed>
	{
		private readonly IDocumentSession _modelSession;

		public RenameForAssignedBuildsQueryUpdater(IDocumentSession modelSession)
		{
			_modelSession = modelSession;
		}

		public bool Handle(SolutionRenamed e)
		{
			string indexName = typeof(Queries.BuildsAssignedToSolution).Name;
			Presentation.Models.Admin.Build[] assignedBuilds = _modelSession.Query<Presentation.Models.Admin.Build>(indexName)
					.Where(v => v.AssignedTo.Id == e.ReceiverId.ToString())
					.ToArray();

			Array.ForEach(assignedBuilds, build => build.AssignedTo.Name = e.NewName);

			return true;
		}
	}
}
